package controller

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"log"
	"math"
	"medical/abac"
	"medical/service"
	"net/http"
	"path"
	"reflect"
	"strconv"
	_ "strconv"
	"strings"
	"time"

	"github.com/jmoiron/sqlx"
)

var cuser User
var registuser User
var data Data
var insti string

func (app *Application) LoginView(w http.ResponseWriter, r *http.Request) {

	ShowView(w, r, "login.html", nil)
}

// index2
func (app *Application) Homeindex(w http.ResponseWriter, r *http.Request) {
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	ShowView(w, r, "menu/Homeindex.html", data)
}

// index
func (app *Application) Index(w http.ResponseWriter, r *http.Request) {
	loginName := r.FormValue("loginName")
	password := r.FormValue("password")
	fmt.Println("the loginname is ", loginName, " and the password is ", password)
	result, _ := app.Setup.UserLogin(loginName, password)
	var flag bool
	flag = result
	data.Flag = false
	data.CurrentUser.Identity = ""
	data.CurrentUser.Password = ""
	if flag {
		// 登录成功
		// TODO: 这里路由有问题，改一下。

		// 添加对用户信息的展示 BY Jack 20230218
		result, _ := app.Setup.UserLoginInfo()
		data.CurrentUser.LoginName = result[0]
		data.CurrentUser.Identity = result[1]
		//BlockInfo, err := app.Setup.InitUpload(result[0], result[2])
		//if err != nil {
		//	fmt.Println(err.Error())
		//} else {
		//	fmt.Println(BlockInfo.FirstBlock, BlockInfo.SecondBlock, BlockInfo.ThirdBlock)
		//}
		//data.BlockInfo = BlockInfo
		ShowView(w, r, "index.html", data)
		// app.Index(w, r)
	} else {
		// 登录失败
		data.Flag = true
		data.CurrentUser.LoginName = loginName
		ShowView(w, r, "login.html", data)
		// app.LoginView(w, r)
	}
}

// 用户登录
func (app *Application) Login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------------调用controllerhandle login-----------------")
	loginName := r.FormValue("loginName")
	password := r.FormValue("password")
	fmt.Println("the loginname is ", loginName, " and the password is ", password)
	result, _ := app.Setup.UserLogin(loginName, password)
	var flag bool
	flag = result
	data.Flag = false
	data.CurrentUser.Identity = ""
	data.CurrentUser.Password = ""
	if flag {
		// 登录成功
		// TODO: 这里路由有问题，改一下。

		// 添加对用户信息的展示 BY Jack 20230218
		result, _ := app.Setup.UserLoginInfo()
		data.CurrentUser.LoginName = result[0]
		data.CurrentUser.Identity = result[1]

		ShowView(w, r, "index.html", data)
		// app.Index(w, r)
	} else {
		// 登录失败
		data.Flag = true
		data.CurrentUser.LoginName = loginName
		ShowView(w, r, "login.html", data)
		// app.LoginView(w, r)
	}
}

// 用户登出
func (app *Application) LoginOut(w http.ResponseWriter, r *http.Request) {
	cuser = User{}
	result, _ := app.Setup.UserLoginOut()
	if result {
		ShowView(w, r, "login.html", nil)
	}
}

// 忘记密码? Forgotpassword 改逻辑 By J 230314
func (app *Application) Forgotpassword(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	data.Flag = true
	identity := r.FormValue("identity")
	realname := r.FormValue("realname")
	phone := r.FormValue("phone")
	identity = strings.Replace(identity, "\n", "", -1)
	realname = strings.Replace(realname, "\n", "", -1)
	phone = strings.Replace(phone, "\n", "", -1)

	// 待修改——前端数据与数据库应有判断
	// 注意前端判断：cuser.Identity 和 cuser.Phone 如果不匹配，请赋值为“”
	if identity == "请输入身份证号" && realname == "请输入真实姓名" && phone == "请输入验证手机号" {
		data.Flag = true // 操作失败
	} else if identity != "请输入身份证号" && realname != "请输入真实姓名" && phone == "请输入验证手机号" {
		flag, _ := app.Setup.UserPwResetId(identity, realname)
		data.Flag = !flag
		cuser.Identity = identity
		if !flag {
			cuser.Identity = ""
		}
	} else if identity == "请输入身份证号" && realname == "请输入真实姓名" && phone != "请输入验证手机号" {
		flag, _ := app.Setup.UserPwResetPhone(phone)
		data.Flag = !flag
		cuser.Phone = phone
		if !flag {
			cuser.Phone = ""
		}
	}
	//else {
	//	ShowView(w, r, "forgotpassword.html", data)
	//}
	if data.Flag {
		ShowView(w, r, "forgotpassword.html", data)
	} else {
		ShowView(w, r, "changepassword.html", data)
	}
}

// 更改密码 Changepassword
func (app *Application) Changepassword(w http.ResponseWriter, r *http.Request) {
	fristpwd := r.FormValue("firstPwd")
	secondpwd := r.FormValue("secondPwd")
	data.Flag = false
	if fristpwd == secondpwd && len(fristpwd) >= 6 && len(fristpwd) <= 30 && fristpwd != "" {
		flag, err := app.Setup.UserPwReset(fristpwd, cuser.Identity, cuser.Phone)
		if err != nil {
			fmt.Printf(err.Error())
		}
		if flag {
			data.Flag = true
			ShowView(w, r, "login.html", data)
		} else {
			ShowView(w, r, "changepassword.html", data)
		}
	} else {
		ShowView(w, r, "changepassword.html", data)
	}
}

// 注册 Register 修改空值判断并限制直接跳转 By J 230314
func (app *Application) Register(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------------调用controllerhandle Register-----------------")
	// 先把机构拿到
	data.Msg, _ = app.Setup.GetAllInsti()
	data.Flag = false
	org := r.FormValue("org")
	identity := r.FormValue("identity")
	password := r.FormValue("password")
	certpassword := r.FormValue("certpassword")
	realname := r.FormValue("realname")
	phone := r.FormValue("phone")
	if org == "组织机构" || password == "6-30位密码" || identity == "请输入18位身份证号" || password == "" || password != certpassword || realname == "真实姓名" || phone == "11位手机号" {
		data.Flag = false
	} else {
		result, RegistResult := app.Setup.UserRegister(phone, identity)
		data.CurNumber = RegistResult // 这里是注册结果的显示
		insti = strings.TrimSpace(org)
		registuser.LoginName = realname
		registuser.Password = password
		registuser.Phone = phone
		registuser.Identity = identity
		fmt.Println(registuser)
		data.Flag = result
	}

	if data.Flag {
		ShowView(w, r, "verify.html", data)
	} else {
		ShowView(w, r, "register.html", data)
	}

}

// 身份验证 Verify
func (app *Application) Verify(w http.ResponseWriter, r *http.Request) {
	authen := r.FormValue("verify")
	certauthen := r.FormValue("certverify")
	role := r.FormValue("userrole")
	fmt.Println(authen, certauthen)
	fmt.Println(insti, role)
	flag := false
	if authen == certauthen {
		result, _ := app.Setup.UserVerify(authen, insti, registuser.LoginName, registuser.Password, registuser.Identity, registuser.Phone, role)
		flag = result
	}
	data.Flag = flag
	if flag {
		ShowView(w, r, "login.html", data)
	} else {
		ShowView(w, r, "verify.html", data)
	}
}

// 添加机构 Register
func (app *Application) Addinstitution(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------------调用controllerhandle Addinstitution-----------------")
	instiname := r.FormValue("instiname")
	instifile := r.FormValue("file1")
	idfile := r.FormValue("idfile")
	var FileAllow map[string]bool = map[string]bool{
		".png": true,
		".jpg": true,
	}
	flag := 0
	if idfile != "" {
		if instifile != "" {
			ext := strings.ToLower(path.Ext(instifile))
			_, ok := FileAllow[ext]
			ext1 := strings.ToLower(path.Ext(idfile))
			_, ok1 := FileAllow[ext1]
			if ok && ok1 {
				flag = 1
			} else {
				fmt.Println("文件后缀名不符合上传要求")
			}
		} else {
			fmt.Println("未选择机构证件")
		}
	} else {
		fmt.Println("未选择身份证件")
	}

	if flag == 1 {
		if instiname != "" && instiname != "请输入添加的机构名称" {
			result, _ := app.Setup.Addinstitution(instiname)
			if result {
				data.Msg, _ = app.Setup.GetAllInsti()
				ShowView(w, r, "register.html", data)
			} else {
				ShowView(w, r, "addinstitution.html", nil)
			}
		} else {
			fmt.Println("未输入机构名")
			ShowView(w, r, "addinstitution.html", nil)
		}
	} else {
		ShowView(w, r, "addinstitution.html", nil)
	}
}

/*
	添加菜单栏跳转
	By Jack
	02-17
*/
// 00-简单搜索展示 SimpleSearch
func (app *Application) SimpleSearch(w http.ResponseWriter, r *http.Request) {

	ShowView(w, r, "menu/SearchDisplay.html", data)
}

// 00-高级搜索展示 显示页面为: AdvancedSearch.html
func (app *Application) AdvancedSearch(w http.ResponseWriter, r *http.Request) {

	ShowView(w, r, "menu/AdvancedSearch.html", data)
}

// 01-队列信息展示 显示页面为: QueueDisplay.html
func (app *Application) QueueDisplay(w http.ResponseWriter, r *http.Request) {

	ShowView(w, r, "menu/QueueDisplay.html", data)
}

// 01-区块信息展示 显示页面为: BlockDisplay.html
func (app *Application) BlockDisplay(w http.ResponseWriter, r *http.Request) {
	data.BlockInfo = app.Setup.GetBlockInto()
	ShowView(w, r, "menu/BlockDisplay.html", data)
}

// 01-本地存储详情 显示页面为: LocalStorage.html
func (app *Application) LocalStorage(w http.ResponseWriter, r *http.Request) {

	ShowView(w, r, "menu/LocalStorage.html", data)
}

// 02-医疗数据上传 显示页面为:02医疗数据上传.html
func (app *Application) UploadMed(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------------调用controllerhandle UploadMed-----------------")
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	data.Flag = true
	data.Msg = ""
	// TODO：这里要用go解析文件然后将文件内容存到数据库中，然后在baseinfo里加一个数据本体，之后按格式插入即可
	// TODO：这里还没做，暂时先空着------>在做ing
	// TODO：subject目前由后端生成为当前时间戳
	// subjectmark := strconv.FormatInt(time.Now().Unix(), 10)
	// datafiles := r.FormValue("check")
	// fmt.Println("datafiles is set to: ", datafiles)
	if r.Method == "GET" {
		ShowView(w, r, "02医疗数据上传.html", data)
		fmt.Println("----zhanshiyemian")
	} else if r.Method == "POST" {
		// ShowView(w, r, "02医疗数据上传.html", data)

		fmt.Println("解析文件")
		icon, file, err := r.FormFile("datafiles")
		if err != nil {
			//返回错误
			// c.JSON(500,gin.H{"error":"get file info fail "+err.Error()})
			fmt.Println("err is ", err.Error())
		}
		defer icon.Close()
		fmt.Println("上传文件名:", file.Filename)
		//限制上传文件类型
		var FileAllow map[string]bool = map[string]bool{
			".xlsx": true,
			".xls":  true,
			".csv":  true,
		}
		ext := strings.ToLower(path.Ext(file.Filename))
		if _, ok := FileAllow[ext]; !ok {
			fmt.Println("文件后缀名不符合上传要求")
			return
		}
		// 读文件内容
		fileContent, _ := file.Open()
		// TODO: 这里仅用csv测试了，后期测一下exl
		r1 := csv.NewReader(fileContent)
		content, err := r1.ReadAll()
		if err != nil {
			log.Fatalf("can not readall, err is %+v", err)
		}
		for _, row := range content[1:][:] {
			fmt.Println(row)
			// info, err := app.Setup.UploadMed(arr[:])
			info, err := app.Setup.UploadMed(row[:])
			fmt.Println("info is ", info)
			if info == "" {
				data.Msg = "该数据标识已存在"
				app.DataUploadErr(w, r)

			} else if err != nil {
				data.Msg = "策略文件未生成"
				app.DataUploadErr(w, r)
			} else {
				transactionID := strings.Split(info, "-")[0]
				policy := strings.Split(info, "=")[1]
				fmt.Println("policy is ", policy)
				var p abac.Policy
				err = json.Unmarshal([]byte(policy), &p)
				data.Msg = "信息添加成功:" + transactionID
				data.Policy = p
				//信誉值改变：若上传成功，当前用户（机构）的信誉值变为原来的3/2
				DB := service.InitDB()
				var CurrentCredit float64
				rows := DB.QueryRow("select Credit from credit_table where TargetOrg='" + result[2] + "'")
				rows.Scan(&CurrentCredit)
				update_rows := "update credit_table set Credit=? where TargetOrg=?"
				DBresult, err := DB.Exec(update_rows, CurrentCredit*3/2, result[2])
				if err != nil {
					fmt.Println("update credit_table failed:", err)
				}
				DBresultrow, err := DBresult.RowsAffected()
				if err != nil {
					fmt.Println("row failed:", err)
				}
				fmt.Println("update credit_table success:", DBresultrow)

				app.DataUpload(w, r)

			}
			fmt.Println("上传数据后生成的策略为：", data.Policy)
		}

	}
	// ShowView(w, r, "02医疗数据上传.html", data)

}

// 02-数据上传 显示页面为:数据上传.html
func (app *Application) DataUploadErr(w http.ResponseWriter, r *http.Request) {
	fmt.Println("进入数据上传页面")
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	fmt.Println("数据为：", data.Msg)
	ShowView(w, r, "数据上传失败.html", data)
}

// 02-数据上传 显示页面为:数据上传.html
func (app *Application) DataUpload(w http.ResponseWriter, r *http.Request) {
	fmt.Println("进入数据上传页面")
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	fmt.Println("数据为：", data.Msg)
	ShowView(w, r, "数据上传.html", data)
}

// 02-医疗数据管理 显示页面为: 02医疗数据管理.html
func (app *Application) ManageMed(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------------调用controllerhandle ManageMed-----------------")
	// TODO: 如果用户未登录，则跳转至登陆界面
	// if cuser.LoginName == "" {
	// 	ShowView(w, r, "login.html", nil)
	// 	return
	// }
	data.Flag = true
	data.Msg = ""
	// tabledata, err := app.Setup.QueryAllMed()
	tabledata, err := app.Setup.QueryAllMed()
	// tabledata_bytes, _ := json.Marshal(tabledata)
	// tabledata_str := string(tabledata_bytes)
	if err != nil {
		data.Msg = err.Error()
	} else {
		// fmt.Println("info is ", tabledata_str)
		data.Table = tabledata
	}
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	ShowView(w, r, "02医疗数据管理.html", data)
}

// 02-访问控制管理 显示页面为: AccessControlManagement.html
func (app *Application) AccessControlManagement(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------------调用AccessControlManagement-----------------")
	data.Table = nil
	// TODO: 如果用户未登录，则跳转至登陆界面
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	data.Flag = true
	// 获取表格数据
	fmt.Println("---------------开始获取table-----------------")

	tabledata, err := app.Setup.QueryAllMed()
	if err != nil {
		data.Msg = err.Error()
	} else {
		// fmt.Println("info is ", tabledata_str)
		data.Table = tabledata
	}
	ShowView(w, r, "menu/AccessControlManagement.html", data)

	fmt.Println("---------------table获取-----------------")
	// 确定这样实现？我把前端关于这里的调用都改成了get By J 0302
	// if r.Method == "GET" {
	// 	fmt.Println("---------------刷新页面-----------------")
	// } else if r.Method == "POST" {
	// fmt.Println("---------------选择数据-----------------")
	// dataId := r.FormValue("dataId")
	// dataName := r.FormValue("dataName")
	// option := r.FormValue("option")
	// // dataId_str := strings.Split(dataId, ",")
	// fmt.Println("dataId is ", dataId, "and the dataName is ", dataName, " and the option is ", option)
	// if option == "read" {
	// 	policy, err := app.Setup.QueryPolicy(dataName)
	// 	if err != nil {
	// 		fmt.Println("policy查询失败：", err.Error())
	// 	}
	// 	fmt.Println("policy is", policy)

	// 	var p abac.Policy
	// 	err = json.Unmarshal([]byte(policy), &p)
	// 	// data.Msg = "信息添加成功:" + transactionID
	// 	data.Policy = p
	// 	ShowView(w, r, "menu/AccessControlManagement.html", data)

	// } else if option == "updata" {
	// 	// dataName_str := strings.Split(dataName, ",")
	// 	// for _, v := range dataName_str {
	// 	// 	policy, err := app.Setup.QueryPolicy(v)
	// 	// 	if err != nil {
	// 	// 		fmt.Println("policy查询失败：", err.Error())
	// 	// 	}

	// 	// }
	// 	data.Msg = dataId + "/" + dataName
	// 	app.UpdatePolicy(w, r)

	// }

	// }

	// if dataId != "" {
	// 	data.Msg = dataId + "/" + dataName
	// 	app.UpdatePolicy(w, r)
	// } else {
	// 	fmt.Println("---------------刷新页面-----------------")
	// 	ShowView(w, r, "menu/AccessControlManagement.html", data)

	// }
}
func (app *Application) ViewPolicy(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------------调用controllerhandle ViewPolicy-----------------")

	dataId := r.FormValue("dataId")
	dataName := r.FormValue("dataName")
	// option := r.FormValue("option")
	fmt.Println("dataId is ", dataId, "and the dataName is ", dataName)
	policy, err := app.Setup.QueryPolicy(dataName)
	if err != nil {
		fmt.Println("policy查询失败：", err.Error())
	}
	fmt.Println("policy is", policy)

	var p abac.Policy
	err = json.Unmarshal([]byte(policy), &p)
	// data.Msg = "信息添加成功:" + transactionID
	data.Policy = p
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	// ShowView(w, r, "menu/AccessControlManagement.html", data)
	ShowView(w, r, "策略查看.html", data)

}

// 02-访问策略生成 显示页面为02访问策略生成.html
func (app *Application) UpdatePolicy(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------------调用controllerhandle UpdatePolicy-----------------")
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	data.Flag = true
	dataId_str := r.FormValue("dataId1")
	// ID是Subject，name是CaseNumber
	dataName_str := r.FormValue("dataName1")
	fmt.Println("dataId is ", dataId_str, "and dataName is ", dataName_str)
	if dataId_str != "" {
		data.Msg = dataId_str + "%" + dataName_str

	}
	ShowView(w, r, "02访问策略生成.html", data)
	fmt.Println(data.Msg)

	arr := [19]string{r.FormValue("startTime"), r.FormValue("endTime"), r.FormValue("firstOrg"), r.FormValue("secondOrg"), r.FormValue("thirdOrg"), r.FormValue("forthOrg"), r.FormValue("adminRead"), r.FormValue("adminWrite"), r.FormValue("adminDelete"), r.FormValue("u1Read"), r.FormValue("u1Write"), r.FormValue("u1Delete"), r.FormValue("u2Read"), r.FormValue("u2Write"), r.FormValue("u2Delete"), r.FormValue("u3Read"), r.FormValue("u3Write"), r.FormValue("u3Delete"), r.FormValue("flag1")}
	fmt.Println(" the arr is ", arr)
	if arr[18] != "" {
		dataId := strings.Split(strings.Split(data.Msg, "%")[0], ",")
		dataName := strings.Split(strings.Split(data.Msg, "%")[1], ",")
		fmt.Println("dataId is ", dataId, "and the dataName is ", dataName)
		for k, v := range dataId {
			fmt.Println("========================================更新", v, "的访问策略================================")
			policy, err := app.Setup.UpdataPolicy(v, dataName[k], arr[:])
			if err != nil {
				fmt.Println("policy更新失败：", err.Error())
			}
			// fmt.Println("msg is: ", info)

			// transactionID := strings.Split(info, "=")[0]
			// policy := strings.Split(info, "=")[1]
			fmt.Println("policy is ", policy)
			var p abac.Policy
			err = json.Unmarshal([]byte(policy), &p)
			data.Policy = p
		}
		ShowView(w, r, "策略查看.html", data)

	}

}

// 02-数据加密共享 显示页面为: EncryDataShared.html
func (app *Application) EncryDataShared(w http.ResponseWriter, r *http.Request) {
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	data.Table, _ = app.Setup.GetShareData()
	ShowView(w, r, "menu/EncryDataShared.html", data)
}
func (app *Application) ChangeDataShared(w http.ResponseWriter, r *http.Request) {
	casenumber := r.FormValue("dataId2")
	//fmt.Println(casenumber)
	arr := [5]string{r.FormValue("3day"), r.FormValue("1week"), r.FormValue("1month"), r.FormValue("3month"), r.FormValue("6month")}
	del := r.FormValue("delete")
	var timechoose string
	if del != "" {
		flag, _ := app.Setup.DeleteShareData(casenumber)
		if !flag {
			fmt.Println("无法删除")
		}

	} else {
		if arr[0] != "" {
			timechoose = "0,0,3"
		} else if arr[1] != "" {
			timechoose = "0,0,7"
		} else if arr[2] != "" {
			timechoose = "0,1,0"
		} else if arr[3] != "" {
			timechoose = "0,3,0"
		} else if arr[4] != "" {
			timechoose = "0,6,0"
		}
		//fmt.Println(timechoose)
		flag, _ := app.Setup.ChangeShareData(casenumber, timechoose)
		if !flag {
			fmt.Println("无法修改时间")
		}
	}

	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	data.Table, _ = app.Setup.GetShareData()
	ShowView(w, r, "menu/EncryDataShared.html", data)
}

// 02-显示共享数据 显示页面为: GenerateShareData.html
func (app *Application) ShowShareData(w http.ResponseWriter, r *http.Request) {
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	data.Table, _ = app.Setup.GetOtherUnShareData()
	ShowView(w, r, "menu/GenerateShareData.html", data)
}
func (app *Application) GenerateShareData(w http.ResponseWriter, r *http.Request) {
	// 获取所选casenumber \ timechoose
	casenumber := r.FormValue("dataName2")
	fmt.Println(casenumber)
	arr := [5]string{r.FormValue("3day"), r.FormValue("1week"), r.FormValue("1month"), r.FormValue("3month"), r.FormValue("6month")}
	var timechoose string
	if arr[0] != "" {
		timechoose = "0,0,3"
	} else if arr[1] != "" {
		timechoose = "0,0,7"
	} else if arr[2] != "" {
		timechoose = "0,1,0"
	} else if arr[3] != "" {
		timechoose = "0,3,0"
	} else if arr[4] != "" {
		timechoose = "0,6,0"
	}
	fmt.Println(timechoose)
	flag, _ := app.Setup.GenerateShareData(casenumber, timechoose)
	if !flag {
		fmt.Println("共享数据无法写入")
	}
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	data.Table, _ = app.Setup.GetOtherUnShareData()
	ShowView(w, r, "menu/GenerateShareData.html", data)
}

// 03-医疗数据溯源 显示页面为: MedicalDataTraceability.html
func (app *Application) MedicalDataTraceability(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------------调用controllerhandleMedicalDataTrace-----------------")
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	data.Msg = ""
	data.Flag = false
	data.History = true
	if result[1] == "u3" {
		data.Msg = "抱歉，您的u3角色无法溯源"
	} else {
		tabledata, err := app.Setup.GetAllDataForTrace()
		if err != nil {
			data.Msg = err.Error()
		} else {
			data.Table = tabledata
		}
	}
	ShowView(w, r, "menu/MedicalDataTraceability.html", data)
}

// 03-01 溯源结果展示 显示页面为: 03溯源结果展示.html
func (app *Application) DisplayMedicalDataTraceability(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------------调用TraceResult-----------------")
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	data.Msg = ""
	caseNumer := r.FormValue("dataName2")
	fmt.Println(caseNumer)
	data.CurNumber = caseNumer
	var his service.MedicalRecordHistoryArr
	var err error
	his, err = app.Setup.OperateMed(caseNumer, result[0], result[2])
	fmt.Println("the result is:", his)
	if err != nil {
		data.Msg = err.Error()
		data.Flag = true
	}
	//var medhis = service.MedicalRecordHistoryArr{}
	//json.Unmarshal(his, &medhis)
	data.MedHis = his.MRH
	// 设置获取前端时限
	var findHis = []service.MedicalRecordHistory{}
	t := time.Now()
	timeOptions := [5]time.Time{t.AddDate(0, 0, -3), t.AddDate(0, 0, -7), t.AddDate(0, -1, 0), t.AddDate(0, -3, 0), t.AddDate(-1, 0, 0)} //3天，1星期，1个月，3个月，1年内5个选项
	var timeChoice time.Time
	arr := [5]string{r.FormValue("3day"), r.FormValue("1week"), r.FormValue("1month"), r.FormValue("3month"), r.FormValue("6month")}
	var timechoose string // 这里参考对时间的处理办法 flag, _ := app.Setup.GenerateShareData(casenumber, timechoose)
	if arr[0] != "" {
		timechoose = "0,0,3" // 三天内
		timeChoice = timeOptions[0]
		data.Msg = "三天内"
	} else if arr[1] != "" {
		timechoose = "0,0,7" // 一星期内
		timeChoice = timeOptions[1]
		data.Msg = "一星期内"
	} else if arr[2] != "" {
		timechoose = "0,1,0" // 一个月内
		timeChoice = timeOptions[2]
		data.Msg = "一个月内"
	} else if arr[3] != "" {
		timechoose = "0,3,0" // 三个月内
		timeChoice = timeOptions[3]
		data.Msg = "三个月内"
	} else if arr[4] != "" {
		timechoose = "1,0,0" // 一年内
		timeChoice = timeOptions[4]
		data.Msg = "一年内"
	}
	fmt.Println(timechoose)
	fmt.Println(timeChoice)
	if len(data.MedHis) > 0 {
		pos := len(data.MedHis) - 1
		tcur, _ := time.Parse("2006-01-02 15:04:05", data.MedHis[pos].Txtime)
		for ; pos >= 0 && timeChoice.Before(tcur); pos-- {
			findHis = append(findHis, data.MedHis[pos])
			tcur, _ = time.Parse("2006-01-02 15:04:05", data.MedHis[pos].Txtime)
		}
	}
	data.MedHis = findHis
	ShowView(w, r, "03溯源结果展示.html", data)
}

// 03-医疗数据审计 显示页面为: MedicalDataAudit.html
func (app *Application) MedicalDataAudit(w http.ResponseWriter, r *http.Request) {
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	data.Msg, _ = app.Setup.GetAllInsti()
	data.Flag = false
	data.History = false
	data.AuditString = "AuditReport"
	ShowView(w, r, "menu/MedicalDataAudit.html", data)
}

// 04-搜索结果展示 显示页面为: SearchDisplay.html
func (app *Application) SearchDisplay(w http.ResponseWriter, r *http.Request) {
	// to solve the problem should do but not

	ShowView(w, r, "menu/SearchDisplay.html", data)
}

// 04-搜索结果展示-获取共享数据 显示页面为: AccessRecordDisplay.html
func (app *Application) SubmitSecShare(w http.ResponseWriter, r *http.Request) {

	fmt.Println("===================ShowShareData=============================")
	casenumbers := r.FormValue("ShareDatacasenumber")
	enterSec := r.FormValue("secShareData")
	fmt.Println(casenumbers, enterSec)

	result, _ := app.Setup.UserLoginInfo()

	flag, Msg, thisresult := app.Setup.MatchGetShareData(casenumbers, enterSec, result[0], result[2])
	data.Msg = Msg
	data.Table = thisresult
	if flag {
		ShowView(w, r, "menu/AccessRecordDisplay.html", data)
	} else {
		ShowView(w, r, "menu/SearchDisplay.html", data)
	}

}

// 04-访问记录展示 显示页面为: AccessRecordDisplay.html
func (app *Application) AccessRecordDisplay(w http.ResponseWriter, r *http.Request) {
	fmt.Println("===================AccessRecordDisplay=============================")
	data.Table = nil
	casenumbers := r.FormValue("dataId1")
	fmt.Println("casenum is ", casenumbers)
	caseNum := strings.Split(casenumbers, ",")
	// tabledata, err := app.Setup.QueryAllMed()
	// var tabledata []service.TableRow
	// v -- casenumber, k -- index
	for k, v := range caseNum {
		if v == "" {
			continue
		}
		var tabledata service.TableRow
		tabledata.FirstColumn = strconv.Itoa(k)
		// tabledata.FifthColumn = k
		fmt.Println("k is ", k, " and v is ", v)
		subjectMark, accessflag, resultAccess := app.Setup.ReadMed(v)
		tabledata.SecondColumn = subjectMark
		tabledata.ThirdColumn = v
		tabledata.FourthColumn = accessflag
		tabledata.FifthColumn = resultAccess
		fmt.Println("strbyte is ", subjectMark)
		data.Table = append(data.Table, tabledata)
	}

	ShowView(w, r, "menu/AccessRecordDisplay.html", data)
}

// 04-操作记录展示 显示页面为: OperationRecordDisplay.html
func (app *Application) OperationRecordDisplay(w http.ResponseWriter, r *http.Request) {
	fmt.Println("===================OperationRecordDisplay=============================")
	data.Table = nil
	table, err := app.Setup.OperationRecord()
	if err != nil {
		fmt.Println("OperationRecordDisplay err is ", err.Error())
	}
	data.Table = table
	ShowView(w, r, "menu/OperationRecordDisplay.html", data)
}

// 05-用户信息更正 显示页面为: ChangeUserInfo.html
func (app *Application) ChangeUserInfo(w http.ResponseWriter, r *http.Request) {
	originpassword := r.FormValue("originpassword")
	search := r.FormValue("search")
	//job := r.FormValue("job")
	newpassword := r.FormValue("newpassword")
	cerpassword := r.FormValue("cerpassword")
	newphone := r.FormValue("newphone")
	result, _ := app.Setup.UserLoginInfo()
	username := result[0]
	data.CurrentUser.LoginName = username
	data.Msg = result[2]

	originpassword = strings.Replace(originpassword, "\n", "", -1)
	search = strings.Replace(search, "\n", "", -1)
	newpassword = strings.Replace(newpassword, "\n", "", -1)
	cerpassword = strings.Replace(cerpassword, "\n", "", -1)
	newphone = strings.Replace(newphone, "\n", "", -1)

	if originpassword != "" && originpassword != "6-30位密码" {
		if newpassword != originpassword && newpassword == cerpassword && len(newpassword) >= 6 && len(newpassword) <= 30 {
			result, _ := app.Setup.Changepassword(username, originpassword, newpassword)
			fmt.Println(result)
		} else {
			fmt.Println("输入密码有误")
		}
	} else if newphone != "11位手机号" && newphone != "" {
		result, _ := app.Setup.Changephone(username, newphone)
		fmt.Println(result)
	} else if search != "关键字由 ，隔开" && search != "" {
		result, _ := app.Setup.Changedisease(username, search)
		fmt.Println(result)
	}

	ShowView(w, r, "menu/ChangeUserInfo.html", data)
}

// 05-用户信息验证 显示页面为: VerifyUserInfo.html
func (app *Application) VerifyUserInfo(w http.ResponseWriter, r *http.Request) {

	ShowView(w, r, "menu/VerifyUserInfo.html", data)
}

// 05-用户信息展示 显示页面为: DisplayUserInfo.html
func (app *Application) DisplayUserInfo(w http.ResponseWriter, r *http.Request) {

	ShowView(w, r, "menu/DisplayUserInfo.html", data)
}

// END

// 暂时弃用 By Jack 02-17

func (app *Application) OperateMed(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	ShowView(w, r, "operateMed.html", data)
}

func (app *Application) AccessMed(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	data.Msg = ""
	data.Flag = false
	data.History = false
	ShowView(w, r, "accessMed.html", data)
}

/*
func (app *Application) AccessMedResult(w http.ResponseWriter, r *http.Request) {
	//arr := [4]string{r.FormValue("operationRecordID"), cuser.LoginName, r.FormValue("organisationID"), r.FormValue("medicalRecordID")}
	var result []byte
	var err error
	result, err = app.Setup.OperateMed("arr[:]")
	fmt.Println("the result is:", result)
	if err != nil {
		data.Msg = err.Error()
		data.Flag = true
	}
	var medhis = service.MedicalRecordHistoryArr{}
	json.Unmarshal(result, &medhis)
	data.MedHis = medhis.MRH
	var med = service.MedicalRecord{}
	json.Unmarshal(result, &med)
	data.Med = med
	if err != nil {
		data.Msg = err.Error()
		data.Flag = true
	}
	if reflect.DeepEqual(med, service.MedicalRecord{}) {
		if data.History {
			ShowView(w, r, "accessMedHistory.html", data)
		} else {
			ShowView(w, r, "accessMed.html", data)
		}
	} else {
		ShowView(w, r, "accessMedResult.html", data)
	}
	ShowView(w, r, "03溯源结果展示.html", data)
}
*/

func (app *Application) DeleteMed(w http.ResponseWriter, r *http.Request) {
	fmt.Println("---------------调用controllerhandle DeleteMed-----------------")
	//r.ParseForm()
	data.Flag = true
	data.Msg = ""
	data.CurNumber = r.FormValue("dataNum2") //此时要修改的医疗记录信息为casenumber
	casenumber := data.CurNumber
	//fmt.Println(data.CurrentUser)
	//data.CurrentUser = cuser
	//caseNumber := r.FormValue("dataNum2")
	fmt.Println("caseNumber值为：")
	fmt.Println(data.CurNumber)
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	arr := [2]string{data.CurrentUser.LoginName, casenumber}
	transactionID, err := app.Setup.DeleteMed(arr[:])
	if err != nil {
		data.Msg = err.Error()
	} else {
		data.Msg = "信息删除成功:" + transactionID
		tabledata, err := app.Setup.QueryAllMed()
		// tabledata_bytes, _ := json.Marshal(tabledata)
		// tabledata_str := string(tabledata_bytes)
		if err != nil {
			data.Msg = err.Error()
		} else {
			// fmt.Println("info is ", tabledata_str)
			data.Table = tabledata
		}
	}
	ShowView(w, r, "02医疗数据管理.html", data)
	//app.ManageMed(w, r)
}

func (app *Application) UpdateMed(w http.ResponseWriter, r *http.Request) {
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]
	fmt.Println("-------------------------UpdateMed---------------")
	DB := service.InitDB()
	cs := service.MedicalRecord{}
	data.Flag = true
	if len(r.FormValue("dataNum1")) > 0 {
		data.CurNumber = r.FormValue("dataNum1") //此时要修改的医疗记录信息为casenumber
	}
	if data.CurNumber != "" {
		casenumber := data.CurNumber
		fmt.Println("待修改的id：" + casenumber)
		arr := [5]string{casenumber, data.CurrentUser.LoginName, r.FormValue("disease"), r.FormValue("group"), r.FormValue("diagnose")}
		fmt.Println(arr)
		if len(data.CurNumber) > 0 && (len(arr[2]) > 0 || len(arr[3]) > 0 || len(arr[4]) > 0) {
			transactionID, err := app.Setup.UpdateMed(arr[:])
			if err != nil {
				data.Msg = err.Error()
			} else {
				data.Msg = "信息修改成功:" + transactionID
			}
		}
		mp := service.SelectDBSingleRecord(DB, data.CurNumber)
		if mp != nil {
			cs = *mp
			data.Case = cs
		}
		data.Flag = false
		data.Msg = "已更新完成"
	}
	if !data.Flag {
		//信誉值改变：若更新成功，当前用户（机构）的信誉值增加0.05
		var CurrentCredit float64
		rows := DB.QueryRow("select Credit from credit_table where TargetOrg='" + result[2] + "'")
		rows.Scan(&CurrentCredit)
		update_rows := "update credit_table set Credit=? where TargetOrg=?"
		DBresult, err := DB.Exec(update_rows, CurrentCredit+0.05, result[2])
		if err != nil {
			fmt.Println("update credit_table failed:", err)
		}
		DBresultrow, err := DBresult.RowsAffected()
		if err != nil {
			fmt.Println("row failed:", err)
		}
		fmt.Println("update credit_table success:", DBresultrow)
	}
	ShowView(w, r, "updateMed.html", data)
}

func (app *Application) AuditMed(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	ShowView(w, r, "auditMed.html", data)
}

func (app *Application) AccessMedHistory(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	data.Msg = ""
	data.Flag = false
	data.History = true
	ShowView(w, r, "accessMedHistory.html", data)
}

func (app *Application) AuditAllRecords(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	data.Msg = ""
	data.Flag = false
	data.History = false
	data.AuditString = "AuditAll"
	ShowView(w, r, "auditAllRecords.html", data)
}

func (app *Application) AuditTimeRangeStartEnd(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	data.Msg = ""
	data.Flag = false
	data.History = false
	data.AuditString = "AuditTimeRangeStartEnd"
	ShowView(w, r, "auditTimeRangeStartEnd.html", data)
}

func (app *Application) AuditByUser(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	data.Msg = ""
	data.Flag = false
	data.History = false
	data.AuditString = "AuditByUser"
	ShowView(w, r, "auditByUser.html", data)
}

func (app *Application) AuditByPatient(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	data.Msg = ""
	data.Flag = false
	data.History = false
	data.AuditString = "AuditByPatient"
	ShowView(w, r, "auditByPatient.html", data)
}

func (app *Application) AuditByOrganisation(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	data.Msg = ""
	data.Flag = false
	data.History = false
	data.AuditString = "AuditByOrganisation"
	ShowView(w, r, "auditByOrganisation.html", data)
}

func (app *Application) AuditByMedicalRecord(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	data.Msg = ""
	data.Flag = false
	data.History = false
	data.AuditString = "AuditByMedicalRecord"
	ShowView(w, r, "auditByMedicalRecord.html", data)
}

func (app *Application) AuditByOriginalAuthor(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	data.Msg = ""
	data.Flag = false
	data.History = false
	data.AuditString = "AuditByOriginalAuthor"
	ShowView(w, r, "auditByOriginalAuthor.html", data)
}

func (app *Application) AuditResult(w http.ResponseWriter, r *http.Request) {
	if data.AuditString == "AuditAll" {
		arr := [3]string{r.FormValue("auditRecordID"), cuser.LoginName, r.FormValue("organisationID")}
		result, err := app.Setup.AuditAll(arr[:])
		var ops = service.OperationRecordArr{}
		json.Unmarshal(result, &ops)
		data.Ops = ops
		data.CurrentUser = cuser
		data.Msg = ""
		data.Flag = false
		if err != nil {
			data.Msg = err.Error()
			data.Flag = true
		}
		if reflect.DeepEqual(data.Ops, service.OperationRecordArr{}) {
			ShowView(w, r, "auditAllRecords.html", nil)
		} else {
			ShowView(w, r, "auditResult.html", data)
		}
	} else if data.AuditString == "AuditTimeRangeStartEnd" {
		arr := [5]string{r.FormValue("auditRecordID"), cuser.LoginName, r.FormValue("organisationID"), r.FormValue("startTimePoint"), r.FormValue("endTimePoint")}
		result, err := app.Setup.AuditTimeRange(arr[:])
		var ops = service.OperationRecordArr{}
		json.Unmarshal(result, &ops)
		data.Ops = ops
		data.CurrentUser = cuser
		data.Msg = ""
		data.Flag = false
		if err != nil {
			data.Msg = err.Error()
			data.Flag = true
		}
		if reflect.DeepEqual(data.Ops, service.OperationRecordArr{}) {
			ShowView(w, r, "auditTimeRangeStartEnd.html", nil)
		} else {
			ShowView(w, r, "auditResult.html", data)
		}
	} else if data.AuditString == "AuditByMedicalRecord" {
		arr := [4]string{r.FormValue("auditRecordID"), cuser.LoginName, r.FormValue("organisationID"), r.FormValue("str")}
		result, err := app.Setup.AuditMedicalRecord(arr[:])
		var ops = service.OperationRecordArr{}
		json.Unmarshal(result, &ops)
		data.Ops = ops
		data.CurrentUser = cuser
		data.Msg = ""
		data.Flag = false
		if err != nil {
			data.Msg = err.Error()
			data.Flag = true
		}
		if reflect.DeepEqual(data.Ops, service.OperationRecordArr{}) {
			ShowView(w, r, "auditByMedicalRecord.html", nil)
		} else {
			ShowView(w, r, "auditResult.html", data)
		}
	} else if data.AuditString == "AuditByUser" {
		arr := [4]string{r.FormValue("auditRecordID"), cuser.LoginName, r.FormValue("organisationID"), r.FormValue("str")}
		result, err := app.Setup.AuditUser(arr[:])
		var ops = service.OperationRecordArr{}
		json.Unmarshal(result, &ops)
		data.Ops = ops
		data.CurrentUser = cuser
		data.Msg = ""
		data.Flag = false
		if err != nil {
			data.Msg = err.Error()
			data.Flag = true
		}
		if reflect.DeepEqual(data.Ops, service.OperationRecordArr{}) {
			ShowView(w, r, "auditByUser.html", nil)
		} else {
			ShowView(w, r, "auditResult.html", data)
		}
	} else if data.AuditString == "AuditByPatient" {
		arr := [4]string{r.FormValue("auditRecordID"), cuser.LoginName, r.FormValue("organisationID"), r.FormValue("str")}
		result, err := app.Setup.AuditPatient(arr[:])
		var ops = service.OperationRecordArr{}
		json.Unmarshal(result, &ops)
		data.Ops = ops
		data.CurrentUser = cuser
		data.Msg = ""
		data.Flag = false
		if err != nil {
			data.Msg = err.Error()
			data.Flag = true
		}
		if reflect.DeepEqual(data.Ops, service.OperationRecordArr{}) {
			ShowView(w, r, "auditByPatient.html", nil)
		} else {
			ShowView(w, r, "auditResult.html", data)
		}
	} else if data.AuditString == "AuditByOrganisation" {
		arr := [4]string{r.FormValue("auditRecordID"), cuser.LoginName, r.FormValue("organisationID"), r.FormValue("str")}
		result, err := app.Setup.AuditOrganisation(arr[:])
		var ops = service.OperationRecordArr{}
		json.Unmarshal(result, &ops)
		data.Ops = ops
		data.CurrentUser = cuser
		data.Msg = ""
		data.Flag = false
		if err != nil {
			data.Msg = err.Error()
			data.Flag = true
		}
		if reflect.DeepEqual(data.Ops, service.OperationRecordArr{}) {
			ShowView(w, r, "auditByOrganisation.html", nil)
		} else {
			ShowView(w, r, "auditResult.html", data)
		}
	} else if data.AuditString == "AuditByOriginalAuthor" {
		arr := [4]string{r.FormValue("auditRecordID"), cuser.LoginName, r.FormValue("organisationID"), r.FormValue("str")}
		result, err := app.Setup.AuditOriginalAuthor(arr[:])
		var ops = service.OperationRecordArr{}
		json.Unmarshal(result, &ops)
		data.Ops = ops
		data.CurrentUser = cuser
		data.Msg = ""
		data.Flag = false
		if err != nil {
			data.Msg = err.Error()
			data.Flag = true
		}
		if reflect.DeepEqual(data.Ops, service.OperationRecordArr{}) {
			ShowView(w, r, "auditByOriginalAuthor.html", nil)
		} else {
			ShowView(w, r, "auditResult.html", data)
		}
	} else {
		ShowView(w, r, "auditMed.html", nil)
	}
}

// *新增：调用两次查询函数，返回指定时间段、指定组织的审计报告
func (app *Application) AuditReportResult(w http.ResponseWriter, r *http.Request) {
	if data.AuditString == "AuditReport" {
		//arr := []string{r.FormValue("auditRecordID0"), cuser.LoginName, r.FormValue("organisationID"), r.FormValue("startTime"), r.FormValue("endTime")}
		//result0, err0 := app.Setup.AuditTimeRange(arr[:])
		//var ops0 = service.OperationRecordArr{}
		//json.Unmarshal(result0, &ops0)
		//arr = []string{r.FormValue("auditRecordID0") + "000", cuser.LoginName, r.FormValue("organisationID"), r.FormValue("auditOrg")}
		//result1, err1 := app.Setup.AuditOrganisation(arr[:])
		//var ops1 = service.OperationRecordArr{}
		//json.Unmarshal(result1, &ops1)

		//fmt.Println("按时间范围审计结果：", ops0)
		//fmt.Println("按机构审计结果：", ops1)
		//由于按时间范围审计功能可能失效，暂时放弃取两次审计结果的交集
		//ops := intersection(ops0, ops1)

		//获取当前用户信息，暂时用于生成操作记录
		user_info, _ := app.Setup.UserLoginInfo()

		var ops = service.OperationRecordArr{}

		//调用智能合约AccessMedicalRecord，获取操作信息
		//使用用户输入的CaseNumber查询相关数据的操作记录
		queryCaseNumber := r.FormValue("auditRecordID0")
		medhis, _ := app.Setup.AccessMedicalRecord(queryCaseNumber, user_info[0], user_info[2])
		startTime, errST := time.Parse("2006-01-02 15:04:05", r.FormValue("startTime")+" 00:00:00")
		if errST != nil {
			fmt.Println(errST.Error())
		}
		endTime, errET := time.Parse("2006-01-02 15:04:05", r.FormValue("endTime")+" 00:00:00")
		if errET != nil {
			fmt.Println(errET.Error())
		}
		for _, mrh := range medhis.MRH {
			mrhTime, errMT := time.Parse("2006-01-02 15:04:05", mrh.Txtime)
			if errMT != nil {
				fmt.Println(errMT.Error())
			}
			//判断当前操作记录是否属于用户要审计的机构（即auditOrg）的人员
			if mrh.Txvalue.Organization == r.FormValue("auditOrg") {
				//判断是否在时间范围内
				if mrhTime.Unix() >= startTime.Unix() && mrhTime.Unix() <= endTime.Unix() {
					var test0 = service.OperationRecord{OperationRecordID: mrh.Txid, UserID: mrh.Txvalue.Researcher, OrganizationID: mrh.Txvalue.Organization, DataType: "医疗记录", ActionType: mrh.Txvalue.OperationType, MedicalRecordID: mrh.Txvalue.CaseNumber, OriginalAuthorID: mrh.Txvalue.Researcher, PatientID: "TEST_PID", EntryMethod: "auto", IsSuccess: mrh.Txvalue.OperationResult == "Success", Time: mrh.Txtime}
					ops.OperationRecord = append(ops.OperationRecord, test0)
				}
			}
		}

		data.Ops = ops
		data.CurrentUser = cuser
		data.Msg = ""
		data.Flag = false
		//if err0 != nil {
		//	data.Msg = err0.Error()
		//	data.Flag = true
		//}
		//if err1 != nil {
		//	data.Msg = err1.Error()
		//	data.Flag = true
		//}

		var repo = service.AuditReport{}
		repo.AuditorName = r.FormValue("auditorName")
		repo.TargetOrg = r.FormValue("auditOrg")

		// 组织操作信息
		total := 0
		fail := 0

		// m0：每个用户的成功操作数
		// m1：每个用户的失败操作数
		m0 := make(map[string]int, 0)
		m1 := make(map[string]int, 0)

		for _, op := range ops.OperationRecord {
			total++
			m0[op.UserID]++
			if !op.IsSuccess {
				fail++
				m1[op.UserID]++
			}
		}

		curFailRate := float64(0)
		maxFailRate := float64(0)

		for user, v := range m0 {
			curFailRate = float64(m1[user]) / float64(v)
			if curFailRate > maxFailRate {
				maxFailRate = curFailRate
				repo.MaxFailRateUser = user
			}
		}
		repo.MaxFailRate = maxFailRate

		repo.TotalOperations = int64(total)
		repo.FailOperations = int64(fail)
		repo.FailRate = float64(fail) / float64(total)

		var (
			userName  string = "root"
			password  string = "root"
			ipAddrees string = "127.0.0.1"
			port      int    = 3306
			dbName    string = "itbtsql"
		)

		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?allowNativePasswords=true", userName, password, ipAddrees, port, dbName)
		Db, err := sqlx.Open("mysql", dsn)
		if err != nil {
			fmt.Printf("mysql connect failed, detail is [%v]", err.Error())
		} else {
			fmt.Printf("mysql connect success!\n")
		}
		defer Db.Close()

		var intv0 float64
		var intv1 float64
		var Credit float64
		rows, err := Db.Query("select intv0, intv1, Credit from credit_table where TargetOrg='" + repo.TargetOrg + "'")
		if err != nil {
			fmt.Println("select failed:", err)
		}
		for rows.Next() {
			rows.Scan(&intv0, &intv1, &Credit)
			fmt.Println(intv0, intv1, Credit)
		}
		defer rows.Close()

		// 成功率区间
		var intv [2]float64
		intv[0] = intv0
		intv[1] = intv1
		repo.ReferenceRange = intv
		repo.PreviousCredit = Credit

		//成功率高出区间，则信誉值上升，区间变化
		//成功率低出区间，则信誉值降低，区间变化
		//成功率处于区间里，信誉值不变，区间不变
		if 1-repo.FailRate > intv[1] {
			repo.CreditChange = "上升"
			Credit = (Credit + 1 - repo.FailRate) / 2
			intv0 = math.Min(Credit, 1-repo.FailRate)
			intv1 = math.Max(Credit, 1-repo.FailRate)
		} else if 1-repo.FailRate < intv[0] {
			repo.CreditChange = "下降"
			Credit = (Credit + 1 - repo.FailRate) / 2
			intv0 = math.Min(Credit, 1-repo.FailRate)
			intv1 = math.Max(Credit, 1-repo.FailRate)
		} else {
			repo.CreditChange = "不变"
		}
		repo.CurrentCredit = Credit

		sql := "update credit_table set intv0=?, intv1=?, Credit=? where TargetOrg=?"
		result, err := Db.Exec(sql, intv0, intv1, Credit, repo.TargetOrg)
		if err != nil {
			fmt.Println("update credit_table failed:", err)
		}
		row, err := result.RowsAffected()
		if err != nil {
			fmt.Println("row failed:", err)
		}
		fmt.Println("update credit_table success:", row)

		data.Repo = repo

		if reflect.DeepEqual(ops, service.OperationRecordArr{}) {
			ShowView(w, r, "menu/MedicalDataAudit.html", data)
		} else {
			ShowView(w, r, "auditReportResult.html", data)
		}
	} else {
		ShowView(w, r, "auditMed.html", nil)
	}
}

// *新增：同时依照时间段和组织ID审计
func (app *Application) AuditReportByTimeRangeAndOrg(w http.ResponseWriter, r *http.Request) {
	data.CurrentUser = cuser
	data.Msg = ""
	data.Flag = false
	data.History = false
	data.AuditString = "AuditReport"
	ShowView(w, r, "03医疗数据审计.html", data)
}

// *新增：返回两个OperationRecordArr的交集
func intersection(nums1 service.OperationRecordArr, nums2 service.OperationRecordArr) service.OperationRecordArr {

	m := make(map[string]int, 0)

	for _, v := range nums1.OperationRecord {
		m[v.OperationRecordID] += 1
	}

	count := 0 //记录新数组长度
	for _, v := range nums2.OperationRecord {
		if m[v.OperationRecordID] > 0 {
			m[v.OperationRecordID] = 0
			nums1.OperationRecord[count] = v
			count++
		}
	}

	return service.OperationRecordArr{OperationRecord: nums1.OperationRecord[:count]}

}

// choose search method section
func (app *Application) Choose_search_method(w http.ResponseWriter, r *http.Request) {
	select_method := r.FormValue("search_select")
	search_key := r.FormValue("search_key")
	fmt.Print("搜索方法：")
	fmt.Println(select_method)
	fmt.Print("搜索关键字：")
	fmt.Println(search_key)
	method_chose := Strval(select_method)

	//different search based on the posted method above

	if method_chose == "深度搜索" {

		//数据库中的测试数据转变成二维的数组并显示出来
		data_sql := Check_sqldata()

		//将数据库中的数据变为一棵树
		data_sql_tree := Create_Multi_branch_tree(data_sql)
		fmt.Println("深度搜索相关记录：")
		rsc := data_sql_tree.LeafNodeDFS_key(search_key) //...代表使用语法糖进行打散操作，append的是data_sql_tree.LeafNodeDFS_key("天天")中的元素，不是这个数组本身
		fmt.Print("_CaseNumber：")
		fmt.Println(rsc...)
		fmt.Println("查询的对应的记录：")
		rs_sum2 := Check_data(rsc)
		data.SearchTable, _ = app.Setup.GetResearchData(rs_sum2)

	} else if method_chose == "广度搜索" {

		//数据库中的测试数据转变成二维的数组并显示出来
		data_sql := Check_sqldata()

		//将数据库中的数据变为一棵树
		data_sql_tree := Create_Multi_branch_tree(data_sql)
		fmt.Println("广度搜索相关记录：")
		rs := data_sql_tree.LeafNodeBFS_key(search_key)
		fmt.Print("_CaseNumber：")
		fmt.Println(rs...)
		fmt.Println("查询的对应的记录：")
		rs_sum1 := Check_data(rs)
		//fmt.Println("查询的对应的记录：")
		//for _, i := range sql_data {
		//	fmt.Println(i...)
		//}
		data.SearchTable, _ = app.Setup.GetResearchData(rs_sum1)
	}
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]

	if data.CurrentUser.Identity == "u3" {
		table := data.SearchTable
		data.SearchTable = nil
		for _, v := range table {
			if v.SeventhColumn == "已共享" {
				data.SearchTable = append(data.SearchTable, v)
			}
		}
	}

	ShowView(w, r, "menu/SearchDisplay.html", data)
	//ShowView(w, r, "index.html", nil)

}

// advancedsearch section
func (app *Application) AdvancedSearchData(w http.ResponseWriter, r *http.Request) {
	key_1 := r.FormValue("key_1")
	key_2 := r.FormValue("key_2")
	key_3 := r.FormValue("key_3")
	key_4 := r.FormValue("key_4")
	//fmt.Println(key_1)
	//fmt.Println(key_2)
	//fmt.Println(key_3)
	//fmt.Println(key_4)
	select_1 := r.FormValue("select_1")
	select_2 := r.FormValue("select_2")
	select_3 := r.FormValue("select_3")
	select_4 := r.FormValue("select_4")
	//fmt.Println(select_1)
	//fmt.Println(select_2)
	//fmt.Println(select_3)
	//fmt.Println(select_4)
	option_1 := r.FormValue("option_1")
	option_2 := r.FormValue("option_2")
	option_3 := r.FormValue("option_3")
	//fmt.Println(option_1)
	//fmt.Println(option_2)
	//fmt.Println(option_3)

	//拼接sql语句
	var sql_str, final_str string

	if key_1 != "" && key_1 != "请输入搜索关键字" {
		sql_str = SelectTOSql(select_1) + " = '" + Strval(key_1) + "' "
	}
	if key_2 != "" && key_2 != "请输入搜索关键字" {
		sql_str += Strval(option_1) + " " + SelectTOSql(select_2) + " = '" + Strval(key_2) + "' "
	}
	if key_3 != "" && key_3 != "请输入搜索关键字" {
		sql_str += Strval(option_2) + " " + SelectTOSql(select_3) + " = '" + Strval(key_3) + "' "
	}
	if key_4 != "" && key_4 != "请输入搜索关键字" {
		sql_str += Strval(option_3) + " " + SelectTOSql(select_4) + " = '" + Strval(key_4) + "' "
	}

	if sql_str != "" {

		final_str = "select * from base_info where " + sql_str
		fmt.Println(" 拼接sql语句: " + final_str)

		sql_data := CheckSqlData(final_str)
		//fmt.Println("查询的对应的记录：")
		//for _, i := range sql_data {
		//	fmt.Println(i...)
		//}
		data.SearchTable, _ = app.Setup.GetResearchData(sql_data)
	}
	result, _ := app.Setup.UserLoginInfo()
	data.CurrentUser.LoginName = result[0]
	data.CurrentUser.Identity = result[1]

	if data.CurrentUser.Identity == "u3" {
		table := data.SearchTable
		data.SearchTable = nil
		for _, v := range table {
			if v.SeventhColumn == "已共享" {
				data.SearchTable = append(data.SearchTable, v)
			}
		}
	}

	ShowView(w, r, "menu/SearchDisplay.html", data)
}
